package com.manage.server.controller.admin;

import com.manage.entity.User;
import com.manage.server.service.FileStorageService;
import com.manage.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/avatar")
public class UserServiceController {
    @Autowired
    private UserService userService;
    @Autowired
    private FileStorageService fileStorageService;

    // 统一使用 Long userId
    @PostMapping("/{userId}")
    public ResponseEntity<String> uploadAvatar(
            @PathVariable Integer userId,
            @RequestParam("file") MultipartFile file) {
        try {
            String filename = fileStorageService.storeAvatar(file, userId);
            userService.updateUserAvatar(userId, filename);
            return ResponseEntity.ok("头像上传成功: " + filename);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("上传失败: " + e.getMessage());
        }
    }

    @GetMapping("/{userId}")
    public ResponseEntity<Resource> getAvatar(@PathVariable Integer userId) {
        User user = userService.getById(userId);
        if (user == null || user.getAvatar() == null) {
            return ResponseEntity.notFound().build();
        }

        Resource file = fileStorageService.loadAvatar(user.getAvatar());
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + file.getFilename() + "\"")
                .body(file);
    }
}